package com.rabbitmq.demo.push_manual;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import java.io.IOException;

@Slf4j
public class ReceiverPush {

    @RabbitListener(queues="queue")
    public void receive(Message message, Channel channel){
        // 获取消息消费标记
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            byte[] messageBody = message.getBody();
            String msg = new String(messageBody);
            log.info("receive is : {}",msg);
            // 消费成功，手动ack
            channel.basicAck(deliveryTag,false); // 第一个参数为消息标记；第二个参数为false表示仅仅确认当前消息，为true，表示之前所有消息都确认消费成功
        } catch (IOException e) {
            // 消费不成功，手动nack
            try {
                channel.basicNack(deliveryTag,false,true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            e.printStackTrace();
        }

    }
}
